<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2021/1/9  11:16
 */

namespace App\Services\Api;

use App\Models\UserVip;
use App\Models\UserVipInfo;
use App\Models\UserVipUseRecord;

class VipServices
{
    public static function list($param)
    {
        $result = UserVip::where('user_id', $param['user_id'])->select('vip_title', 'vip_maturity','vip_id', 'activate')->get();

        if(empty($result))return [];

        $new_result = [];

        foreach ($result as &$v){
            //会员卡超时了
            if(strtotime("{$v->vip_maturity}") < time())continue;

            //未到激活时间
            if(!empty($v->activate)) {
                if (strtotime("{$v->activate}") > time()) continue;
            }

            $where = [];

            $where[] = ['user_id', $param['user_id']];
            $where[] = ['vip_id', $v->vip_id];
            $where[] = ['class_info_id', $param['class_base_info_id']];

            $user_vip_info = UserVipInfo::where($where)->first();

            if(empty($user_vip_info))continue;

            if(!empty($user_vip_info->is_restriction)){
                if(empty($user_vip_info->num))continue;
            }

            $input = [];

            $input['vip_title'] = $v->vip_title;

            $input['vip_maturity'] = $v->vip_maturity;

            if(!empty($v->activate)) {
                $input['activate'] = $v->activate . " 00:00:00";
            }else{
                $input['activate'] = "";
            }

            $input['num'] = $user_vip_info->num??0;

            $input['vip_id'] = $user_vip_info->vip_id??0;

            $input['is_restriction'] = $user_vip_info->is_restriction??0;

            $new_result[] = $input;
        }

        return $new_result;
    }

    public static function info($user_id, $vip_id)
    {
        $where = [];
        if(!empty($user_id)){
            $where[] = ['user_id', $user_id];
        }
        if(!empty($vip_id)){
            $where[] = ['vip_id', $vip_id];
        }
        return UserVip::where($where)->select('vip_title', 'vip_maturity', 'vip_id', 'activate')->first();
    }


    public static function record($param = [])
    {
        $vip_id = $param['vip_id']??0;

        $query = UserVipUseRecord::where('user_id', auth('api')->user()->id)->where('user_vip_id', $vip_id);

        if (!empty($param['where_date'])) {
            $start=date('Y-m-01 00:00:00',strtotime($param['where_date']));//获取指定月份的第一天
            $end=date('Y-m-t 23:59:59',strtotime($param['where_date'])); //获取指定月份的最后一天

            $query = $query->whereBetween('created_at',[$start,$end]);
        }

        return $query->select("class_name",'user_vip_name', 'is_restriction', 'before_num', 'after_num', 'created_at','remark')->orderBy("id", 'desc')->paginate(6);
    }
}
